package com.pavlinic.mylisp;

import java.util.HashMap;
import java.util.Map;

public class ImmutableEvaluationContext implements EvaluationContext {
	private final Map<? extends String, ? extends Expression> map;

	public ImmutableEvaluationContext() {
		this(new HashMap<String, Expression>());
	}

	protected ImmutableEvaluationContext(Map<String, Expression> newMap) {
		this.map = newMap;
	}

	public ImmutableEvaluationContext withBinding(String name, Expression value) {
		final Map<String, Expression> newMap = new HashMap<String, Expression>();
		newMap.putAll(map);
		newMap.put(name, value);
		return new ImmutableEvaluationContext(newMap);
	}

	public Expression getBinding(String name) {
		return map.get(name);
	}

	@Override
	public String toString() {
		final StringBuilder buf = new StringBuilder();
		for (Map.Entry<? extends String, ? extends Expression> entry : map.entrySet()) {
			buf.append(entry.getKey()).append(": ").append(entry.getValue()).append("\n");
		}
		return buf.toString();
	}

	public boolean hasBinding(String value) {
		return map.containsKey(value);
	}
}
